<template>
  <el-dialog
    title="添加"
    :visible.sync="dialogVisible"
    width="500px"
  >
    <el-form ref="formRef" style="margin-right: 10px" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="ruleForm.deptName" clearable />
      </el-form-item>
      <el-form-item label="显示顺序" prop="orderNum">
        <el-input v-model="ruleForm.orderNum" clearable />
      </el-form-item>
      <el-form-item label="上级部门" prop="parentId">
        <ElSelectTree
          v-model="ruleForm.parentId"
          :data="deptList"
          node-key="deptId"
          :props="{
            label: 'deptName',
            children: 'children'
          }"
          check-strictly
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>

</template>

<script>
import { http_dept } from '@/api';
import { listToTree } from '@/utils';

export default {
  name: 'Dept',
  data() {
    return {
      request: http_dept,
      deleteKey: 'deptId',
      ruleForm: {
        deptId: undefined,
        parentId: '',
        deptName: '',
        orderNum: 0
      },
      resetForm: {
        deptId: undefined,
        parentId: '',
        deptName: '',
        orderNum: 0
      },
      rules: {
        deptName: [
          { required: true, message: '不能为空' }
        ],
        orderNum: [
          { required: true, message: '不能为空' }
        ]
      },
      deptList: [],
      dialogVisible: false
    }
  },
  computed: {
    title() {
      return this.ruleForm[this.deleteKey] ? '编辑' : '添加'
    }
  },
  methods: {
    add() {
      this.getDeptList()
      this.ruleForm = {
        ...this.resetForm
      }
      this.dialogVisible = true
    },
    edit(row) {
      this.getDeptList()

      for (const ruleFormKey in this.ruleForm) {
        this.ruleForm[ruleFormKey] = row[ruleFormKey]
      }
      this.dialogVisible = true
    },
    getDeptList() {
      http_dept.list().then(res => {
        this.deptList = listToTree(res.data || [], 'deptId')
      })
    },
    onSave() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.request[this.ruleForm[this.deleteKey] ? 'update' : 'create']({
            ...this.ruleForm
          }).then((res) => {
            this.$message.success(res.msg)
            this.$emit('get-page')
            this.onClose()
          })
        }
      })
    },
    onClose() {
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped lang="scss">
</style>
